package controller

import (
	"jtvss/api/operation/dto"
	"jtvss/api/operation/model"
	sysmodel "jtvss/api/system/model"
	syservice "jtvss/api/system/service"
	"jtvss/middleware"
	"jtvss/pkg/ctx"
	"jtvss/pkg/orm"
	"jtvss/util"

	"github.com/gin-gonic/gin"
)

// Organization
type Organization struct {
}

// ListHandler 列表
func (o *Organization) ListHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	var data []model.Organization
	toatl, _ := p.DbModelWhere(&model.Organization{}, func(dw *orm.DbWhere) {
		dw.Equal("ParentID", 0) // 上级节点为0，表示公司
		dw.Add("GUID != ?", "")
	}).Find(&data)
	ctx.JSONWriteTotal(toatl, data, c)
}

// GetHandler 详细
func (o *Organization) GetHandler(c *gin.Context) {
	util.QueryByID(&model.Organization{}, c)
}

// AddHandler 新增
func (o *Organization) AddHandler(c *gin.Context) {
	var p model.Organization
	//获取参数
	if err := c.ShouldBind(&p.OrganizationOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	p.GUID = util.UUID()
	tok := middleware.UserToken(c)
	u := &sysmodel.User{}
	u.UserName = p.UserName
	u.CreatedBy = tok.UserName
	u.OrganizeName = p.Name
	u.Type = sysmodel.SysUserTypeAdmin
	u.OrganizeGUID = p.GUID
	u.DeviceIds = "*"
	if err := syservice.SysUserCreate(u); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbCreate(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateHandler 修改
func (o *Organization) UpdateHandler(c *gin.Context) {
	var p model.Organization
	//获取参数
	if err := c.ShouldBind(&p.OrganizationOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateModel(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 删除
func (o *Organization) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.Organization{}, c)
}

func (o Organization) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.DELETE("/:id", o.DeleteHandler)
}
